import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import moment from 'moment';
import { Card, Dialog, InfiniteScroll, SpinLoading } from 'antd-mobile';
import { InbizIcon } from '@inbiz/utils';
import NoData from '../NoData/ListNoData';
import { goto, getSummary, getProcessInfoAfterCustomClickItem } from '../../commonUtils';
import { getFormData } from '../utils';
import { removeDraft, getDraft } from './service';
import { getMessage } from '@inbiz/react';
import './index.less';

const ProcessDraft = forwardRef((props: any, ref) => {
  const { userInfo, rangeConfig, processGroup, customClickItem } = props;
  const [draftData, setDraftData] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [page, setPage] = useState(1);

  let pageCheck = null;

  const formatServer = (
    pageIndex: number,
    data: {
      total: number; rows: any[]
    } = { rows: [], total: 0 },
  ) => {
    const state = data !== null;
    let row: any[] = [];
    let checkDataIsNull: boolean | number = false;
    let changeArr: any[] = [];
    let isAdd = false;

    const nowPage = pageIndex;
    if (state) {
      // 判断请求是否成功
      row = data.rows.map((item) => {
        return {
          ...item,
          summary:
            item.summary && item.summary.startsWith('<')
              ? getSummary(item.summary)
              : item.summary,
        };
      });
      checkDataIsNull = row.length && row.length < 1; // 判断是否有数据
      pageCheck = () => {
        // 处理数据
        if (checkDataIsNull) {
          setHasMore(false);
        } else {
          const more = pageIndex < Math.ceil(data.total / 20);
          changeArr = row;
          setHasMore(more);
          setPage(nowPage + 1);
        }
      };
      // 判断页面为1
      if (nowPage == 1) {
        pageCheck();
      } else {
        isAdd = true;
        pageCheck();
      }
      if (isAdd) {
        // 判断是不是有分页数据
        let _draftData = draftData;
        setDraftData([..._draftData, ...changeArr])
      } else {
        setDraftData(changeArr);
      }
    } else {
      if (pageIndex == 1) {
        setDraftData([]);
      }
    }
  };

  const getList = async (
    value: string,
    pageIndex: number,
    searchC?: any,
  ) => {
    setLoading(true);
    const drparams = getFormData(userInfo, pageIndex, value, searchC);
    let res = await getDraft({
      ...drparams,
      dptKey:
        rangeConfig == 'all' || processGroup?.selectedRows?.length == 0
          ? ''
          : processGroup?.groupGuid ?? '',
    });
    formatServer(pageIndex, res?.details);
    setLoading(false);
  };

  const delDraft = (e: React.MouseEvent, draftsId: string) => {
    e.preventDefault();
    e.stopPropagation();
    Dialog.confirm({
      content: getMessage('processCenter.confirmRemoveDraft'),
      confirmText: React.createElement(
        'span',
        { style: { color: 'var(--inbiz-color-primary)' } },
        getMessage('global.sure'),
      ),
      cancelText: React.createElement('span', {}, getMessage('global.cancel')),
      onConfirm: () => {
        setLoading(true);
        removeDraft({
          drafID: `${draftsId}`,
        }).then(async (res) => {
          if (res.code == '200') {
            await getList('', 1);
          }
          setLoading(false);
        }).catch((error) => { setLoading(false); });
      },
    });
  };

  useEffect(() => {
    getList('', page);
  }, []);

  useImperativeHandle(ref, () => ({
    getList: async (text: string, condition?: any) => {
      getList(text, 1, condition);
    },
  }));

  return (
    <div className={'processDraft'}>
      {loading ? (
        <div className={'loading'}>
          <SpinLoading />
        </div>
      ) : draftData.length > 0 ? (
        <>
          {' '}
          {draftData.map((item: any, index: number) => {
            return (
              <Card
                className={'draftContainer'}
                title={item.processName}
                key={index}
                extra={
                  <InbizIcon
                    type="icon-shanchu-h"
                    style={{ color: '#9b9b9b', fontSize: 16 }}
                    onClick={(e: any) => delDraft(e, item.draftsId)}
                  />
                }
                onClick={async (e) => {
                  if (customClickItem) {
                    const result = await getProcessInfoAfterCustomClickItem({
                      processDefinitionId: item.procDefId,
                      businessKey: item.businessKey,
                      drafID: item.draftsId,
                      inItiateApplication: true,
                      taskState: item.taskState,
                      siteType: 1,
                    });
                    customClickItem({ event: e, processItem: item, requestItem: result });
                  } else {
                    goto(
                      {
                        processDefinitionId: item.procDefId,
                        businessKey: item.businessKey,
                        drafID: item.draftsId,
                        inItiateApplication: true,
                        taskState: item.taskState,
                        siteType: 1,
                      },
                      '4',
                      'wap',
                      e,
                      '',
                      () => { },
                      setLoading,
                    )
                  };
                }}
              >
                {typeof item.summary === 'string' && item.summary !== '' && (
                  <p className={'summary'}>{item.summary}</p>
                )}
                <section className={'cardBody'}>
                  <p>{moment(item.creationTime).format('YYYY-MM-DD HH:mm:ss')}</p>
                </section>
              </Card>
            );
          })}
          <InfiniteScroll loadMore={() => getList('', page)} hasMore={hasMore} />
        </>
      ) : (
        <NoData />
      )}
    </div>
  );
});

export default ProcessDraft;
